package com.cyl.manager.pms.service;

import com.cyl.manager.pms.convert.SkuConvert;
import com.cyl.manager.pms.domain.entity.Sku;
import com.cyl.manager.pms.domain.service.SkuDomainService;
import com.cyl.manager.pms.req.SkuQueryReq;
import com.cyl.manager.pms.req.SkuReq;
import com.cyl.manager.pms.resp.SkuResp;
import com.github.pagehelper.PageHelper;
import com.sincere.common.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * sku信息Service业务层处理
 *
 *
 * @author zcc
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SkuService {

    private final SkuDomainService skuDomainService;

    /**
     * 查询sku信息
     *
     * @param id sku信息主键
     * @return sku信息
     */
    public SkuResp getSkuDetail(Long id) {
        Sku sku = skuDomainService.getById(id);
        return SkuConvert.INSTANCE.entity2Resp(sku);
    }

    /**
     * 查询sku信息列表
     *
     * @param query 查询条件
     * @param page 分页条件
     * @return sku信息
     */
    public Page<SkuResp> querySku(SkuQueryReq query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        List<Sku> skuList = skuDomainService.listByPage(query, page);
        List<SkuResp> respList = SkuConvert.INSTANCE.entityList2RespList(skuList);
        return new PageImpl<>(respList, page, ((com.github.pagehelper.Page) skuList).getTotal());
    }


    /**
     * 导出品牌管理列表
     */
    public List<SkuResp> exportSkuList(SkuQueryReq query) {
        List<Sku> list = skuDomainService.listByPage(query, null);
        return SkuConvert.INSTANCE.entityList2RespList(list);
    }

    /**
     * 新增sku信息
     *
     * @param req sku信息
     * @return 结果
     */
    public boolean save(SkuReq req) {
        Sku sku = SkuConvert.INSTANCE.req2Entity(req);
        sku.setCreateTime(LocalDateTime.now());
        return skuDomainService.save(sku);
    }

    /**
     * 修改sku信息
     *
     * @param req sku信息
     * @return 结果
     */
    public boolean update(SkuReq req) {
        Sku sku = SkuConvert.INSTANCE.req2Entity(req);
        sku.setUpdateTime(LocalDateTime.now());
        sku.setUpdateBy(SecurityUtils.getUserId());
        return skuDomainService.updateById(sku);
    }

    /**
     * 删除sku信息信息
     *
     * @param id sku信息主键
     * @return 结果
     */
    public Boolean deleteById(Long id) {
        Sku sku = skuDomainService.getById(id);
        sku.setDeleted(true);
        sku.setUpdateTime(LocalDateTime.now());
        sku.setUpdateBy(SecurityUtils.getUserId());
        return skuDomainService.updateById(sku);
    }
}
